package Array;

/**
 * @Description TODO
 * @Author zrj
 * @Date 2020/7/29 18:23
 * @Version 1.0
 */
public class ArrayTest<E> {

    private int size;
    private int[] data;

    public ArrayTest(Integer capacity) {
        data =  new int[capacity];
        size = 0;
    }

    public ArrayTest() {
        this(10);
    }

    public void add(int e) {
        this.add(size,e);
    }

    public void addFirst(int e) {
        add(0, e);
    }

    public void addLast(int e) {
        add(size, e);
    }

    public void add(int index , int e) {

        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("add fail!");
        }

        if (size == data.length) {

            resize(size);
        }
        for (int i = size - 1; i >= index; i--) {
            data[i+1] = data[i];
        }

        data[index] = e;
        size++;
    }

    private void resize(int newCapacity) {
        if (size >= data.length) {
            int[] newData = new int[size*2];
            for (int i = 0; i < size; i++) {
                newData[i] = data[i];
            }
            data = newData;
        }
    }

    public int removeFirst() {
        return remove(0);
    }

    public int removeLast() {
        return remove(size - 1);
    }

    public int remove(int index) {
        int e = data[index];
        for (int i = index ; i< size - 1 ; i ++) {
            data[i] = data[i + 1];
        }
        size --;
        if (size == data.length / 2 ) {
            resize(data.length / 2 + 1 );
        }
        return e;
    }

    public static void main(String[] args) {
        ArrayTest arrayTest = new ArrayTest<Integer>();
        for (Integer i = 0; i < 9; i++) {
            arrayTest.add(i);

        }

        System.out.println(arrayTest.toString());
        arrayTest.addFirst(6);
        System.out.println(arrayTest.toString());
        arrayTest.addLast(6);
        arrayTest.addLast(6);
        System.out.println(arrayTest.toString());
        arrayTest.remove(4);
        System.out.println(arrayTest.toString());
        arrayTest.removeFirst();
        System.out.println(arrayTest.toString());
        arrayTest.removeLast();
        System.out.println(arrayTest.toString());



    }

    public String toString() {

        StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (int i = 0; i < size; i++) {

            int e = data[i];
            sb.append( e);
            if (i != size - 1) {
                sb.append(',').append(' ');
            }
        }
        sb.append("]");

        return sb.toString();
    }
}
